package com.liuzhilong.infrastructure.framework.netty.echo.client.handle;

import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;
import lombok.Setter;
import lombok.experimental.Accessors;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.Semaphore;

@ChannelHandler.Sharable // @Sharable 标记这个类的实例可以在channel里共享
@Slf4j
@Setter
@Accessors(chain = true)
public class EchoClientHandler extends SimpleChannelInboundHandler<String> {
    private Semaphore semaphore;
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ctx.writeAndFlush("你好，同志"); // 当被通知该 channel 是活动的时候就发送信息
        ctx.writeAndFlush("\n"); // 当被通知该 channel 是活动的时候就发送信息
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, String msg) throws Exception {
        semaphore.release();
        System.out.println("Client received: " + msg); // 记录接收到的消息
//        channelHandlerContext.writeAndFlush(msg);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        // 记录日志错误并关闭 channel
        log.error("",cause);
        ctx.close();
    }
}
